import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { getDesignStats } from '../services/design';
import { useAuth } from '../contexts/AuthContext';

interface DesignStats {
  total: number;
  completed: number;
  processing: number;
  failed: number;
  pending: number;
}

const DesignStats: React.FC = () => {
  const [stats, setStats] = useState<DesignStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { user } = useAuth();

  useEffect(() => {
    if (user) {
      loadStats();
    }
  }, [user]);

  const loadStats = async () => {
    try {
      setLoading(true);
      const response = await getDesignStats();
      if (response.success) {
        setStats(response.data);
      } else {
        setError(response.message || 'Failed to load statistics');
      }
    } catch (err) {
      setError('Failed to load statistics');
      console.error('Error loading stats:', err);
    } finally {
      setLoading(false);
    }
  };

  const getSuccessRate = () => {
    if (!stats || stats.total === 0) return 0;
    return Math.round((stats.completed / stats.total) * 100);
  };

  const getFailureRate = () => {
    if (!stats || stats.total === 0) return 0;
    return Math.round((stats.failed / stats.total) * 100);
  };

  const getPendingDesigns = () => {
    if (!stats) return 0;
    return stats.pending;
  };

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">Please log in to view your statistics</h2>
          <p className="text-gray-600">You need to be logged in to access your design statistics.</p>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading your statistics...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-red-600 mb-4">Error</h2>
          <p className="text-gray-600 mb-4">{error}</p>
          <button
            onClick={loadStats}
            className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 py-12">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">Design Statistics</h1>
          <p className="text-xl text-gray-600">Track your AI design generation progress and usage</p>
        </div>

        {stats && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
            {/* Total Designs */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.1 }}
              className="bg-white rounded-lg shadow-md p-6 text-center"
            >
              <div className="text-3xl font-bold text-blue-600 mb-2">{stats.total}</div>
              <div className="text-gray-600 font-medium">Total Designs</div>
              <div className="text-sm text-gray-500 mt-1">All time</div>
            </motion.div>

            {/* Completed Designs */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.2 }}
              className="bg-white rounded-lg shadow-md p-6 text-center"
            >
              <div className="text-3xl font-bold text-green-600 mb-2">{stats.completed}</div>
              <div className="text-gray-600 font-medium">Completed</div>
              <div className="text-sm text-gray-500 mt-1">{getSuccessRate()}% success rate</div>
            </motion.div>

            {/* Failed Designs */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.3 }}
              className="bg-white rounded-lg shadow-md p-6 text-center"
            >
              <div className="text-3xl font-bold text-red-600 mb-2">{stats.failed}</div>
              <div className="text-gray-600 font-medium">Failed</div>
              <div className="text-sm text-gray-500 mt-1">{getFailureRate()}% failure rate</div>
            </motion.div>

            {/* Credits Used */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.4 }}
              className="bg-white rounded-lg shadow-md p-6 text-center"
            >
              <div className="text-3xl font-bold text-yellow-600 mb-2">{stats.processing}</div>
              <div className="text-gray-600 font-medium">Processing</div>
              <div className="text-sm text-gray-500 mt-1">In progress</div>
            </motion.div>
          </div>
        )}

        {/* Progress Charts */}
        {stats && stats.total > 0 && (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            {/* Success Rate Chart */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5, delay: 0.5 }}
              className="bg-white rounded-lg shadow-md p-6"
            >
              <h3 className="text-xl font-bold text-gray-900 mb-6">Design Success Rate</h3>
              <div className="space-y-4">
                {/* Completed */}
                <div>
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium text-green-600">Completed</span>
                    <span className="text-sm text-gray-600">{stats.completed} ({getSuccessRate()}%)</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className="bg-green-600 h-2 rounded-full transition-all duration-1000 ease-out"
                      style={{ width: `${getSuccessRate()}%` }}
                    ></div>
                  </div>
                </div>

                {/* Failed */}
                <div>
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium text-red-600">Failed</span>
                    <span className="text-sm text-gray-600">{stats.failed} ({getFailureRate()}%)</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className="bg-red-600 h-2 rounded-full transition-all duration-1000 ease-out"
                      style={{ width: `${getFailureRate()}%` }}
                    ></div>
                  </div>
                </div>

                {/* Processing */}
                <div>
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium text-yellow-600">Processing</span>
                    <span className="text-sm text-gray-600">{stats.processing} ({Math.round((stats.processing / stats.total) * 100)}%)</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className="bg-yellow-600 h-2 rounded-full transition-all duration-1000 ease-out"
                      style={{ width: `${Math.round((stats.processing / stats.total) * 100)}%` }}
                    ></div>
                  </div>
                </div>

                {/* Pending */}
                {getPendingDesigns() > 0 && (
                  <div>
                    <div className="flex justify-between items-center mb-2">
                      <span className="text-sm font-medium text-gray-600">Pending</span>
                      <span className="text-sm text-gray-600">{getPendingDesigns()} ({Math.round((getPendingDesigns() / stats.total) * 100)}%)</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div
                        className="bg-gray-600 h-2 rounded-full transition-all duration-1000 ease-out"
                        style={{ width: `${Math.round((getPendingDesigns() / stats.total) * 100)}%` }}
                      ></div>
                    </div>
                  </div>
                )}
              </div>
            </motion.div>

            {/* Usage Summary */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5, delay: 0.6 }}
              className="bg-white rounded-lg shadow-md p-6"
            >
              <h3 className="text-xl font-bold text-gray-900 mb-6">Usage Summary</h3>
              <div className="space-y-4">
                <div className="flex justify-between items-center py-3 border-b border-gray-200">
                  <span className="text-gray-600">Success rate</span>
                  <span className="font-semibold text-green-600">{getSuccessRate()}%</span>
                </div>
                <div className="flex justify-between items-center py-3 border-b border-gray-200">
                  <span className="text-gray-600">Total designs created</span>
                  <span className="font-semibold text-gray-900">{stats.total}</span>
                </div>
                <div className="flex justify-between items-center py-3 border-b border-gray-200">
                  <span className="text-gray-600">Completed designs</span>
                  <span className="font-semibold text-green-600">{stats.completed}</span>
                </div>
                <div className="flex justify-between items-center py-3">
                  <span className="text-gray-600">Processing designs</span>
                  <span className="font-semibold text-yellow-600">{stats.processing}</span>
                </div>
              </div>
            </motion.div>
          </div>
        )}

        {/* Empty State */}
        {stats && stats.total === 0 && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
            className="text-center py-12"
          >
            <div className="text-gray-400 mb-4">
              <svg className="mx-auto h-24 w-24" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
              </svg>
            </div>
            <h3 className="text-lg font-medium text-gray-900 mb-2">No statistics yet</h3>
            <p className="text-gray-600 mb-6">Start creating designs to see your statistics!</p>
            <a
              href="/design"
              className="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 transition-colors"
            >
              Create Your First Design
            </a>
          </motion.div>
        )}
      </div>
    </div>
  );
};

export default DesignStats;